package com.lhs.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhs.DTO.blog.BlogDTO;
import com.lhs.Result.Result;
import com.lhs.entity.blog.blog_post;
import com.lhs.mapper.blog_post_0Mapper;
import com.lhs.service.ArticleService;
import com.lhs.service.blog_post_0Service;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;



@Service
public class ArticleServiceImpl extends ServiceImpl<blog_post_0Mapper, blog_post>
        implements ArticleService {

     @Autowired
     private blog_post_0Mapper articleMapper;

     @Autowired
     private blog_post_0Service articleService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
public Result schedulePublish(BlogDTO article) {
    article.setStatus(2); // 待发布

    try {
        articleService.addBlog(article);

        long delay = article.getPublishTime().getTime() - System.currentTimeMillis();

        // 处理已过期的发布时间
        if (delay <= 0) {
            return Result.error("发布时间不能早于当前时间");
        }

        // RocketMQ 延时消息
        if (delay <= MAX_DELAY_TIME) {
            rocketMQTemplate.syncSend(
                    "article_publish_topic",
                    MessageBuilder.withPayload(article.getId()).build(),
                    3000,
                    calculateDelayLevel(delay)
            );
        }

        return Result.success("发布成功");
    } catch (Exception e) {
        log.error("定时发布文章失败，文章ID: {}");
        // 考虑是否需要回滚已添加的文章数据
        return Result.error("发布失败：" + e.getMessage());
    }
}

private static final long MAX_DELAY_TIME = 2 * 60 * 60 * 1000; // 2小时


    private int calculateDelayLevel(long delay) {
        if (delay <= 1000) return 1;   // 1s
        else if (delay <= 5000) return 2;  // 5s
        else if (delay <= 10000) return 3; // 10s
        else if (delay <= 30000) return 4; // 30s
        else if (delay <= 60000) return 5; // 1m
        else if (delay <= 120000) return 6; // 2m
        else if (delay <= 300000) return 7; // 5m
        else if (delay <= 600000) return 8; // 10m
        else if (delay <= 1800000) return 9; // 30m
        else if (delay <= 3600000) return 10; // 1h
        else return 11; // 2h
    }
}
